<template>
  <div class="product_browse">
    <loading v-if="loading"></loading>
    <div class="tabbar" v-if="showTabs">
      <tabs v-model="active" color="#283C79" @change="onTabChange">
        <tab :title="item.categoryName" v-for="(item,index) in categoryList" :key="index"></tab>
        <!-- <tab title="提货"></tab> -->
      </tabs>
    </div>

    <div class="products-list">
      <div
        v-if="productsList.length != 0"
        class="item"
        v-for="(item,index) in productsList"
        :key="index"
      >
        <product-item :cover="staticHost + item.goodsImg">
          <div class="product-info" slot="product-item">
            <div class="name">{{item.goodsName}}</div>
            <div class="p-info">
              <p class="spec">{{item.size}}</p>
              <p class="delete" v-if="item.price">￥{{item.price}}</p>
              <div class="price">
                <div>
                  <p>￥{{item.presentPrice}}</p>
                  <!-- <span class="delete">￥{{item.presentPrice}}</span> -->
                </div>
                <!-- <p class="status">
                  <span>库存：999组</span>
                  <span class="sign">已售罄</span>
                </p>-->
                <div class="add">
                  <!-- <stepper v-model="value" button-size="22px" /> -->
                  <div
                    class="add-cart"
                    v-if="isDirect == 'N'"
                    @click="popupType = 'addGoods', showPopup = true, selectedAddCart = item"
                  >加入到进货</div>
                  <div
                    class="add-cart"
                    v-if="isDirect == 'Y'"
                    @click="popupType = 'addCart', showPopup = true, selectedAddCart = item"
                  >加入购物车</div>
                </div>
              </div>
            </div>

            <!-- <div class="num">
              <stepper v-model="value" button-size="22px" />
            </div>-->
          </div>
        </product-item>
      </div>
      <div class="be-short" v-if="!productsList">
        <!-- <p><img src="../img/我要进货@2x.png" alt=""></p> -->
        <p class="wait">Wait.</p>
        <p>暂时没有产品</p>
        <p>耐心等待系统进货</p>
      </div>
    </div>

    <div
      class="add-operation"
      v-if="isDirect == 'N'"
      @click="popupType = 'addGoodsCart', showPopup = true"
    >
      <p>
        <img src="../img/我要进货@2x.png" alt />
      </p>
      <p>
        <span>进货购物车</span>
        <p class="dot">{{cartList.length}}</p>
      </p>
    </div>

    <div class="add-operation" v-if="isDirect == 'Y'" @click="goToShoppingCart">
      <p>
        <img src="../img/我要进货@2x.png" alt />
      </p>
      <p>
        <span>查看购物车</span>
        <p class="dot">{{cartList.length}}</p>
      </p>
    </div>

    <popup :show="showPopup" @onCancel="onCancel">
      <div v-if="popupType == 'addGoods'">
        <div class="carry-goods">
          <div class="header">加入进货</div>
          <div class="content">
            <product-item :cover="staticHost+selectedAddCart.goodsImg">
              <div class="product-info" slot="product-item">
                <div class="name">{{selectedAddCart.goodsName}}</div>
                <div class="p-info">
                  <p class="spec">{{selectedAddCart.size}}</p>
                  <p class="delete" v-if="selectedAddCart.price">￥{{selectedAddCart.price}}</p>
                  <div class="price">
                    <div>
                      <p>￥{{selectedAddCart.presentPrice}}</p>
                    </div>
                    <div class="add"></div>
                  </div>
                </div>
              </div>
            </product-item>

            <div class="carry-number">
              <p>进货数量</p>
              <p>
                <stepper v-model="selectedGoodsNumber" />
              </p>
            </div>
          </div>
          <div class="carry-goods-operation">
            <p @click="onCancel">取消</p>
            <p @click="onAddConfirm">确定</p>
          </div>
        </div>
      </div>

      <div v-if="popupType == 'addCart'">
        <div class="carry-goods">
          <div class="header">加入购物车</div>
          <div class="content">
            <product-item :cover="staticHost+selectedAddCart.goodsImg">
              <div class="product-info" slot="product-item">
                <div class="name">{{selectedAddCart.goodsName}}</div>
                <div class="p-info">
                  <p class="spec">{{selectedAddCart.size}}</p>
                  <p class="delete" v-if="selectedAddCart.price">￥{{selectedAddCart.price}}</p>
                  <div class="price">
                    <div>
                      <p>￥{{selectedAddCart.presentPrice}}</p>
                    </div>
                    <div class="add"></div>
                  </div>
                </div>
              </div>
            </product-item>

            <div class="carry-number">
              <p>购买数量</p>
              <p>
                <stepper v-model="selectedGoodsNumber" />
              </p>
            </div>
          </div>
          <div class="carry-goods-operation">
            <p @click="onCancel">取消</p>
            <p @click="onAddConfirm">确定</p>
          </div>
        </div>
      </div>
      <div v-if="popupType == 'addGoodsCart'">
        <div class="carry-cart">
          <div class="header">进货购物车</div>
          <div class="content">
            <div class="cart-nothing" v-if="cartList.length == 0">暂无商品</div>
            <div class="cart-list" v-if="cartList.length != 0">
              <swipe-cell v-for="(item,index) in cartList" :key="index">
                <product-item v-if="item.goodsImg" :cover="staticHost+item.goodsImg">
                  <div class="product-info" slot="product-item">
                    <div class="name">{{item.goodsName}}</div>
                    <div class="p-info">
                      <p class="spec">{{item.size}}</p>
                      <p class="delete" v-if="item.price">￥{{item.price}}</p>
                      <div class="price">
                        <div>
                          <p>￥{{item.presentPrice}}</p>
                        </div>
                        <div class="add">
                          <stepper v-model="item.number" @change="onStepperChange" />
                        </div>
                      </div>
                    </div>
                  </div>
                </product-item>

                <template slot="right">
                  <van-button type="danger" text="删除" @click="deleteFromCart(item.id)" />
                </template>
              </swipe-cell>
            </div>
          </div>
          <div class="carry-cart-operation">
            <!-- <p @click="onCancel">取消</p>
            <p @click="onCartConfirm">确定</p>-->
            <div class="total">
              <div>
                <p>合计：</p>
                <p>
                  <span>￥</span>
                  <span>{{addGoodsTotalPrice}}</span>
                </p>
              </div>
              <div @click="onAddSubmit">进货结算</div>
            </div>
          </div>
        </div>
      </div>
    </popup>
  </div>
</template>

<script>
import http from "../service/myHttp.js";
import urls from "../service/url.js";
import { mapState } from "vuex";
import { Tab, Tabs, Stepper, Button, SwipeCell, SubmitBar, Toast } from "vant";
import popup from "../components/popup.vue";
import productItem from "../components/product_item.vue";
import { staticHost } from "../service/HOST.js";
var _ = require("lodash");
var remove = require("lodash.remove");
import loading from "../components/loading.vue";

export default {
  components: {
    Tab,
    Tabs,
    productItem,
    Stepper,
    vanButton: Button,
    popup,
    SwipeCell,
    SubmitBar,
    loading
  },
  data() {
    return {
      loading: true,
      showTabs: false,
      active: 0,
      showPopup: false,
      popupType: "",
      selectedGoodsNumber: 1,
      staticHost,
      categoryId: this.$route.query.id,
      categoryName: this.$route.query.name,
      isDirect: this.$route.query.isDirect,
      categoryList: [],
      productsList: [],
      value: 0,
      cartList: [
        // {
        //   name: "TIMELESS时光番茄口服美白丸",
        //   cate: "一箱 30包",
        //   num: 1
        // }
      ],
      selectedAddCart: {},
      mallType: [{
        id: 0,
        name: '直购类',
        isDirect: 'Y',
        
      },{
        id: 1,
        name: '非直购类',
        isDirect: 'N', 
      }],
    };
  },
  computed: {
    ...mapState({
      userInfo: state => state.login_module.userinfo,
      countAlias: "userInfo"
    }),
    addGoodsTotalPrice() {
      let price = 0;
      if (this.cartList.length) {
        this.cartList.forEach(item => {
          price += item.presentPrice * item.number;
        });
      }
      return Number(price).toFixed(2);
    }
  },
  watch: {
    showPopup(newVal) {
      if (!newVal) {
        this.selectedGoodsNumber = 1;
      }
    }
  },
  async mounted() {
    // 初始化
    if (this.isDirect == "N") {
      // 初始化 标题和导航栏
      let title = "商品进货";
      this.$store.commit("setNavInfo", {
        title: title
      });
      document.title = title + " - TIMELESS 分销商城";
      await this.getProductCategory();

      // 初始化 购物车 localstorage
      this.cartList = localStorage.getItem("addGoods")
        ? JSON.parse(localStorage.getItem("addGoods"))
        : [];
    } else {
      let title = "商品直购";
      this.$store.commit("setNavInfo", {
        title: title
      });
      document.title = title + " - TIMELESS 分销商城";
      await this.getProductCategory();

      this.cartList = localStorage.getItem("addCart")
        ? JSON.parse(localStorage.getItem("addCart"))
        : [];
    }

    // 初始化 选择品类
    if (this.categoryId) {
      this.active = _.findIndex(this.categoryList, o => {
        return o.id == this.categoryId;
      });
    } else {
      this.active = 0;
      this.categoryId = this.categoryList[this.active].id;
    }

    this.categoryName = this.categoryList[this.active].categoryName;

    // 获取商品列表
    await this.getProductsList();

    this.loading = false
    this.showTabs = true
  },
  methods: {
    // 购物车商品数量发生变化时
    onStepperChange() {
      // 更新localStorage里的值
      this.saveCartToStorage();
    },
    // 进货购物车 结算
    onAddSubmit() {
      this.showPopup = false;
      if (this.cartList.length) {
        this.$router.push({
          path: "/settlement",
          query: {
            shopType: "shopAdd"
          }
        });
      } else {
        Toast("进货购物车不能为空");
      }
    },

    // popup 单个商品选择  comfirm
    onAddConfirm() {
      Toast.success("加入成功");
      // 点击 加入到进货 时
      if (this.popupType == "addGoods") {
        this.saveCartToCartList();
      }
      // 点击 加入购物车 时
      else if (this.popupType == "addCart") {
        this.saveCartToCartList();
      }

      // 更新localStorage里的值
      this.saveCartToStorage();

      this.showPopup = false;
    },
    // 购物车商品列表 保存到 this.cartList
    saveCartToCartList() {
      let number = this.selectedGoodsNumber;
      let index = _.findIndex(this.cartList, o => {
        return o.id == this.selectedAddCart.id;
      });
      // 购物车中是否已存在该种商品
      if (index != -1) {
        this.cartList[index].number += number;
      } else {
        this.selectedAddCart.number = number;
        let cartItem = _.cloneDeep(this.selectedAddCart);
        this.cartList.push(cartItem);
      }
    },

    // 持久化储存 购物车
    saveCartToStorage() {
      // localStorage.setItem(this.popupType, JSON.stringify(this.cartList));
      if (this.popupType == "addGoods" || this.popupType == "addGoodsCart") {
        localStorage.setItem("addGoods", JSON.stringify(this.cartList));
      } else if (this.popupType == "addCart") {
        localStorage.setItem("addCart", JSON.stringify(this.cartList));
      }
    },
    // 购物车删除商品
    deleteFromCart(id) {
      let index = _.findIndex(this.cartList, o => {
        return o.id == id;
      });
      this.cartList.splice(index, 1);

      // 更新localStorage里的值
      this.saveCartToStorage();

      Toast.success("删除成功");
    },
    // popup comfirm
    // onConfirm(value) {
    //   if (this.popupType == "payType") {
    //     this.selectedPayType = value;
    //     // this.payType = this.selectedPayType
    //   } else if (this.popupType == "grade") {
    //     this.selectedAgencyLevel = value;
    //   }
    //   this.showPopup = false;
    //   // this.pageNumber = 1
    //   // this.allList = []

    //   // this.loading = false
    //   // this.finished = false
    // },
    onCancel() {
      this.showPopup = false;
    },
    onTabChange(value) {
      let index = value;
      this.categoryId = this.categoryList[index].id;
      this.categoryName = this.categoryList[index].categoryName;
      this.active = index;

      this.getProductsList();
    },

    // 获取非直购品类类型
    getProductCategory() {
      return http.post(urls.HQSCPL, {}).then(res => {
        let categoryList = res.data.data;
        categoryList.forEach(item => {
          if (item.isDirect == this.isDirect) {
            this.categoryList.push(item);
          }
        });
      });
    },

    // 获取商品列表
    getProductsList() {
      return http
        .post(urls.CKPLSP, {
          categoryId: this.categoryId,
          levelId: this.userInfo.agentLevel
        })
        .then(res => {
          this.productsList = res.data.data;
        });
    },
    goToShoppingCart() {
      this.$router.push({
        path: "/home/shopping_cart"
      });
    }
  }
};
</script>

<style scoped>
.tabbar {
  position: sticky;
  top: 0;
}

.products-list {
  margin-bottom: 54px;
  margin-top: 5px;
}

.product-item {
  padding-bottom: 10px;
}

.item {
  /* padding: 10px 10px 0 10px; */
  background-color: #fff;
}

.p-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  /* align-items: center; */
}

.name {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 1rem;
  color: #3b3d4e;
}

.spec {
  /* margin-bottom: 10px; */
  font-size: 0.9rem;
}

.price {
  /* flex: 1; */
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.price>div > p:last-child {
  color: var(--money-up);
  font-size: 1rem;
}

.delete {
  font-size: 0.9rem;
  text-decoration: line-through;
  /* padding-left: 10px; */
  display: flex;
  align-items: flex-end;
  flex: 1;
}

.status {
  font-size: 0.9rem;
}

.status .sign {
  background-color: #bebebe;
  color: #fff;
  padding: 0 5px;
  border-radius: 3px;
}

.num {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
  /* margin-bottom: 10px; */
}

.add {
  display: flex;
  justify-content: flex-end;
}

.add-cart {
  background-color: #283c79;
  border-radius: 20px;
  padding: 5px 15px;
  color: #fff;
  font-size: 0.8rem;
}

.add-cart:active {
  background-color: #1a264e;
}

.be-short {
  position: absolute;
  transform: translate(-50%, -50%);
  top: 40%;
  left: 50%;
  text-align: left;
}

.be-short .wait {
  font-size: 3.5rem;
  color: #283c79;
  text-align: left;
  font-weight: bold;
}

.add-operation {
  padding: 12px;
  background-color: #fff;
  position: fixed;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}

.add-operation p:first-child {
  width: 30px;
  height: 30px;
}

.add-operation p:last-child{
  display: flex;
}

.add-operation img {
  width: 100%;
  height: 100%;
}

.product-info {
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  height: 100%;
  padding-left: 12px;
  /* padding: 10px 0 10px 10px; */
}

.product-info > p:first-child {
  color: #5a5d6c;
}

.carry-cart {
  position: relative;
}

.carry-cart .content,
.carry-goods .content {
  padding: 0 0 0 15px;
  /* padding-top: 5px; */
}
.carry-cart .header,
.carry-goods .header {
  padding: 12px;
  /* margin-bottom: 5px; */
  text-align: center;
  color: var(--Emphasize-font);
  font-size: 1.05rem;
  border-bottom: 1px solid var(--line-between-color);
}

.carry-cart .header {
  position: sticky;
  top: 0;
  background-color: #fff;
  z-index: 100;
}

.carry-cart .content {
  /* padding-bottom: 10px; */
  max-height: 435px;
  overflow: scroll;
}

.carry-cart .product-item {
  margin-bottom: 10px;
}

.carry-number {
  padding: 10px 0px;
}

.carry-number p {
  margin-bottom: 10px;
}

.carry-cart-operation,
.carry-goods-operation {
  display: flex;
}
.carry-cart-operation > p,
.carry-goods-operation > p {
  flex: 1;
  text-align: center;
  padding: 12px;
  position: relative;
}
.carry-cart-operation > p:first-child,
.carry-goods-operation > p:first-child {
  background-color: #f7f8fa;
}
.carry-cart-operation > p:first-child:active,
.carry-goods-operation > p:first-child:active {
  background-color: rgb(218, 218, 218);
}
.carry-cart-operation > p:last-child,
.carry-goods-operation > p:last-child {
  background-color: #283c79;
  color: #fff;
}
.carry-cart-operation > p:last-child:active,
.carry-goods-operation > p:last-child:active {
  background-color: rgb(29, 43, 85);
}

.carry-cart-operation {
  width: 100%;
  /* position: fixed; */
  bottom: 0;
}

.cart-detail {
  flex: 1;
  display: flex;
  justify-content: space-between;
}

.product_browse .cart-list {
  max-height: 435px;
  overflow: scroll;
}

.total {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  border-top: 1px solid var(--line-between-color);
}
.total > div {
  padding: 12px;
  display: flex;
}

.total > div:first-child span {
  color: var(--money-up);
}

.total > div:first-child span:first-child {
  font-size: 0.8rem;
}

.total > div:last-child {
  background-color: #283c79;
  color: #fff;
  padding: 12px 30px;
}

.cart-nothing {
  padding: 20px 0 30px 0;
  text-align: center;
}
</style>

<style>
.product_browse .van-button {
  height: 100%;
}

.product_browse .cover img {
  height: 100px;
  width: 105px;
}

.product_browse .van-submit-bar {
  bottom: 0 !important;
  border-top: 1px solid var(--line-between-color);
}

.product_browse .product-item {
  border-bottom: 0;
}

.product_browse .van-submit-bar__button {
  width: 120px;
}
</style>